package com.imooc.dianping.controller.admin;


import com.imooc.dianping.common.AdminPermission;
import com.imooc.dianping.common.BusinessException;
import com.imooc.dianping.common.CommonUtil;
import com.imooc.dianping.common.EmBusinessError;
import com.imooc.dianping.model.Category;
import com.imooc.dianping.request.CategoryCreateReq;
import com.imooc.dianping.request.PageQuery;
import com.imooc.dianping.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin/category")
public class AdminCategoryController {

    @Autowired
    private CategoryService categoryService;

    //品类列表
    @RequestMapping("/index")
    @AdminPermission
    public String index(PageQuery pageQuery, Model model) {
        model.addAttribute("data", categoryService.selectAll(pageQuery));
        model.addAttribute("CONTROLLER_NAME", "category");
        model.addAttribute("ACTION_NAME", "index");
        return "/admin/category/index";
    }

    @RequestMapping("/createpage")
    @AdminPermission
    public String createPage(Model model) {
        model.addAttribute("CONTROLLER_NAME", "category");
        model.addAttribute("ACTION_NAME", "create");
        return "/admin/category/create";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @AdminPermission
    public String create(@Valid CategoryCreateReq categoryCreateReq, BindingResult bindingResult) throws BusinessException {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, CommonUtil.processErrorString(bindingResult));
        }
        Category category = new Category();
        BeanUtils.copyProperties(categoryCreateReq, category);
        categoryService.create(category);
        return "redirect:/admin/category/index";
    }

}
